import io
import logging

from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet
from rest_framework.permissions import IsAuthenticated
from config.dbs.redis_测试 import LOGIN_KEY_TEMPLATE, EXPIRE_TIME
from users.models import UserDetail
from users.serializers import UserSerializer, UserDetailSerializer
from utils.permission import ActiveUserPermission,wrap_permission,TeacherPermission
from utils.verifyUtil import ImageVerify
from rest_framework.status import HTTP_404_NOT_FOUND,HTTP_400_BAD_REQUEST,HTTP_500_INTERNAL_SERVER_ERROR


class ImageVerifyView(View):
    """
    图片验证码的视图类

    get
    返回图片验证码
    """
    def get(self,request,uuid):
        """
        返回图片验证码
        :param request:请求对象
        :param uuid:客户端唯一识别码
        :return:
        """
        imgVerify = ImageVerify()
        img,code = imgVerify.verify_code()

        #将图片数据返回给客户端，无需持久化，使用文件流，因为是图片，是字节数据
        img_bytes = io.BytesIO() #临时文件流
        img.save(img_bytes,format='PNG')#保存
        image_bytes = img_bytes.getvalue()#图片数据

        #如何保存 uuid:Aw2c key-value 临时数据中，缓存在redis当中
        cache = get_redis_connection(alias='verify_codes')
        cache.set(LOGIN_KEY_TEMPLATE % uuid,code,EXPIRE_TIME)
        return HttpResponse(image_bytes,content_type='image/png')



class UserViewSet(ReadOnlyModelViewSet):
    queryset = User.objects.filter(is_active=1)
    serializer_class = UserSerializer
    permission_classes = [IsAuthenticated]

    #老师查看所有人信息
    @wrap_permission(TeacherPermission)
    def list(self, request, *args, **kwargs):
        return ReadOnlyModelViewSet.list(self, request, *args, **kwargs)

    # 自己可以看自己得到信息
    @wrap_permission(ActiveUserPermission)
    def retrieve(self, request, *args, **kwargs):
        return ReadOnlyModelViewSet.retrieve(self, request, *args, **kwargs)

    @wrap_permission(ActiveUserPermission)
    def update(self,request,pk):
        #得到用户 user
        try:
            user = self.get_queryset().get(id=pk)
        except User.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)

        #得到用户输入的数据进行反序列化
        user_serializer = self.get_serializer(user,data=request.data)
        #数据效验
        user_serializer.is_valid(raise_exception=True)
        #修改user表信息
        user_serializer.save()
        #判断用户是否传入详情数据
        user_detail = request.data.get('userdetail')#获取用户传入的详情数据
        if user_detail:
            # 有，判断用户是否有详情数据，判断数据库中有没
            if hasattr(user,'userdetail'):
                # 有，修改
                user_detail_serializer = UserDetailSerializer(user.userdetail,data=user_detail)
            else:
                #没有，增加
                user_detail['user'] = pk #指定用户
                user_detail_serializer = UserDetailSerializer(data=user_detail)
            user_detail_serializer.is_valid(raise_exception=True)
            user_detail_serializer.save()

            user_serializer.data['userdetail'] = UserDetailSerializer(data=user_detail)
        # 返回修改后的数据
        return Response(user_serializer.data)


